const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test',
  password: '123456',
  port: 3307,
});

connection.execute('SHOW TABLES;', (err, rows) => {
  if (err instanceof Error) {
    console.log('execute error:', err);
    return;
  }

  console.log('数据库test已启动');

  if (rows.length === 0) {
    connection.execute(
      'CREATE TABLE qq_list (qq char(20) NOT NULL, name char(50) NOT NULL) ENGINE=InnoDB;',
      (err, rows) => {
        if (err instanceof Error) {
          console.log('execute error:', err);
          return;
        }

        console.log('test数据库创建qq_list表成功');
      }
    );
  }
});

connection.addListener('error', (err) => {
  if (err instanceof Error) {
    console.log(`createConnection error:`, err);
  }
});

function insertIntoDB(qq, name, resolver) {
  const sql = 'INSERT INTO `qq_list`(`qq`, `name`) VALUES (?, ?)';
  if(name.length > 50){
    console.warn('[警告]: ',name, ' is too long!')
    name = name.slice(0, 50)
  }
  const values = [qq, name];
  connection.execute({ sql, values }, (err) => {
    if (err instanceof Error) {
      console.log(`插入数据出错:`, err);
      resolver();
    }
    resolver();
  });
}

function onSave() {
  return new Promise((res) => {
    connection.execute(
      "SELECT DISTINCT Concat(qq,'+',name) AS result FROM qq_list;",
      (err, rows) => {
        if (err instanceof Error) {
          console.log(`createConnection error:`, err);
        }
        res(rows);
      }
    );
  });
}

module.exports = {
  insertIntoDB,
  onSave,
};
